<template>
  <div class="open-urls">
    <el-card shadow="always">
      <h2>输入网址：</h2>
      <el-input
        v-model="urlText"
        type="textarea"
        :rows="10"
        placeholder="https://example1.com
https://example2.com"
        @input="formatURLs"
      />

      <div style="margin-top: 20px;">
        <el-button type="primary" :disabled="!urlText.trim() || !isAdmin" @click="openURLs">
          Open
        </el-button>
        <el-button @click="openURLs(true)">测试 - Open</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'OpenUrls',
  data() {
    return {
      urlText: '',
      apiurl: 'https://webdeploy.bepicgamescn.com'
    }
  },
  computed: {
    isAdmin() {
      return this.$store.getters.roles.join(' | ') === 'admin'
    }
  },
  methods: {
    formatURLs() {
      // 自动格式化为按行分隔
      this.urlText = this.urlText.replace(/\s+/g, '\n')
    },
    async openURLs(isTest = false) {
      const urls = this.urlText
        .split('\n')
        .map(url => url.trim())
        .filter(Boolean)

      if (urls.length === 0) return

      // 打开网址
      urls.forEach(url => {
        let finalUrl = /^https?:\/\//.test(url) ? url : 'https://' + url
        if (isTest) {
          finalUrl += finalUrl.includes('?') ? '&google_console=1' : '?google_console=1'
        }
        window.open(finalUrl, '_blank')
      })

      // 上传日志
      const logEntry = {
        time: new Date().toLocaleString(),
        mode: isTest ? '测试' : '常规',
        urls
      }

      try {
        const res = await fetch(`${this.apiurl}/logs`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(logEntry)
        })
        if (!res.ok) throw new Error('日志上传失败')
      } catch (err) {
        this.$message.error('日志上传失败')
        console.error(err)
      }
    }
  }
}
</script>

<style scoped>
.open-urls {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    padding: 40px 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.el-card {
    width: 100%;
    max-width: 700px;
    padding: 30px 24px;
    border-radius: 16px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
    background-color: #fff;
}

h2 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #333;
}

.el-textarea {
    font-family: monospace;
    font-size: 14px;
    border-radius: 8px;
}

.el-button {
    min-width: 100px;
    margin-right: 12px;
}

.el-button:last-child {
    margin-right: 0;
}
</style>
